package com.blackcat.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * SpringSecurity配置
 * @author blackcat
 * @date 2023/12/25 15:53
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

//    @Autowired
//    private UserAuthService userAuthService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/oauth/**", "/oauth2/**","/login/**", "logout/**").permitAll()    // login 页面，所有用户都可以访问
                //.antMatchers("/home").hasAnyRole("USER", "com.municipal.pojo")   // home 页面，ADMIN 和 USER 都可以访问
                .anyRequest().authenticated()
//                .and()
//                .formLogin()
//                .loginPage("/login") // 自定义登录表单
                //.defaultSuccessUrl("/home", true)  // 登录成功跳转的页面，第二个参数true表示每次登录成功都是跳转到home，如果false则表示跳转到登录之前访问的页面
                //.failureUrl("/login?error=true")
//                .failureHandler(authenticationFailureHandler())  // 失败跳转的页面（比如用户名/密码错误），这里还是跳转到login页面，只是给出错误提示
                .and().logout().permitAll()  // 登出 所有用户都可以访问
                .and().csrf().disable();    // 关闭csrf，此时登出logout接收任何形式的请求；（默认开启，logout只接受post请求）
    }


    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置登陆账户和密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.inMemoryAuthentication().withUser("admin").
                password(encoder.encode("123456")).authorities("ROLE ADMIN");
        //从数据库中读取账户密码
//        auth.userDetailsService(userAuthService);
    }
    //---------------------
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
